package cn.t222.service;

import cn.t222.mapper.SysResourcesMapper;
import cn.t222.pojo.SysResources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
@Service
@CacheConfig(cacheNames = "resource-service")
public class ResourceService {
    @Resource
    private SysResourcesMapper sysResourcesMapper;

    public int add(SysResources resources) {
        return sysResourcesMapper.add(resources);
    }
    public int del(Integer id) {
        return sysResourcesMapper.del(id);
    }
    public int update(SysResources resources) {
        return sysResourcesMapper.update(resources);
    }
    public SysResources get(Integer id) {
        return sysResourcesMapper.get(id);
    }

    public List<SysResources> getAll() {
        return sysResourcesMapper.getAll();
    }

    @Cacheable(key = "targetClass + ':' + methodName + ':' + #username")
    public List<SysResources> getAllByUsername(String username) {
        return sysResourcesMapper.getAllByUsername(username);
    }
    @Cacheable(key = "targetClass + ':' + methodName + ':' + #roleId")
    public List<SysResources> getAllByRoleId(Integer roleId) {
        return sysResourcesMapper.getAllByRoleId(roleId);
    }

    /**
     * 1.删除中间表指定角色所有资源
     * 2.添加资源id到中间表
     * @param roleId
     * @param resourceIds
     * @return
     */
    @Transactional
    @CacheEvict(allEntries = true)
    public int updateResources(Integer roleId, String resourceIds) {
        sysResourcesMapper.delRoleResources(roleId);
        if(resourceIds.trim().length()> 0) {
            String[] ids = resourceIds.split(",");
            for(String id: ids) {
                sysResourcesMapper.addRoleResources(roleId, Integer.parseInt(id));
            }
        }
        return 1;
    }

    @Cacheable(key = "targetClass + ':' + methodName + ':' + #username")
    public List<SysResources> getAllButtonPermissions(String username, String modulePath) {
        return sysResourcesMapper.getAllButtonPermissions(username, modulePath);
    }
}
